package com.situ.mall.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.situ.mall.common.config.AlipayConfigBean;
import com.situ.mall.common.entity.OrderInfo;
import com.situ.mall.common.service.IpayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Service

public class PayServiceImpl implements IpayService {
    @Autowired
    private AlipayConfigBean alipayConfigBean;
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String createPayOrder(OrderInfo order) {

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",alipayConfigBean.getAppId(),alipayConfigBean.getPrivateKey(),"json","UTF-8",alipayConfigBean.getPublicKey(),alipayConfigBean.getSignType());
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl("https://251z5582l6.yicp.fun/order/notify");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getCode());
        bizContent.put("total_amount", order.getPrice().add(BigDecimal.valueOf(100)));
        bizContent.put("subject", "测试商品");


        request.setBizContent(bizContent.toString());
        try {

            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                return response.getQrCode();
            } else {
                System.out.println("调用失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return "";
    }

}
